package org.example.lostandfound.dao;

import org.example.lostandfound.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;//用于执行JDBC操作的Spring工具类

    @Override
    public List<User> findAllUsers() {
        return jdbcTemplate.query("SELECT * FROM users",new UserRowMapper());
    }

    @Override
    public List<User> findUsersByName(String userName) {
        return jdbcTemplate.query("SELECT * FROM users WHERE userName=?",new UserRowMapper(),userName);
    }

    @Override
    public List<User> findUsersById(Long id) {
        return jdbcTemplate.query("SELECT * FROM users WHERE id=?",new UserRowMapper(),id);
    }

    @Override
    public void registerUser(User user) {
        jdbcTemplate.update("INSERT INTO users (username,password,phone_number,email,real_name,grade) VALUES (?,?,?,?,?,?)",
                user.getUserName(),user.getPassword(),user.getPhoneNumber(),user.getEmail(),user.getRealName(),user.getGrade());

    }

    @Override
    public void updateUser(User user) {
        jdbcTemplate.update("UPDATE users SET username=?,password=?,phone_number=?,email=?,real_name=?,grade=? WHERE id =?",
                user.getUserName(),user.getPassword(),user.getPhoneNumber(),user.getEmail(),user.getRealName(),user.getGrade());

    }

    @Override
    public void deleteUser(Long id) {
        jdbcTemplate.update("DELETE FROM users WHERE id=?",id);

    }

    @Override
    public User login(String phoneNumber, String password) {
        return jdbcTemplate.queryForObject("SELECT * FROM users WHERE phone_number=? AND password=?",new UserRowMapper(),phoneNumber,password);
    }

    //创建内部类，实现RowMapper接口，用于将ResultSet中的数据映射到User对象
    private class UserRowMapper implements RowMapper<User> {
        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setUserName(rs.getString("username"));
            user.setPhoneNumber(rs.getString("phone_number"));
            user.setPassword(rs.getString("password"));
            user.setEmail(rs.getString("email"));
            user.setRealName(rs.getString("real_name"));
            user.setGrade(rs.getString("grade"));
            return user;
        }
    }
}
